package com.iot.gateway.tsl.controller;

import com.iot.gateway.tsl.qo.DeviceQo;
import com.iot.gateway.tsl.service.TslDeviceService;
import com.iot.gateway.utils.ApiResult;
import io.swagger.v3.oas.annotations.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/devices")
@Tag(name = "设备管理")
public class TslDeviceController {

    private final TslDeviceService deviceService;

    public TslDeviceController(TslDeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Operation(summary = "新增设备", description = "为系统新增一台设备，并关联到某个产品")
    @PostMapping("/add")
    public ApiResult<Void> addDevice(@Parameter(description = "设备信息", required = true) @RequestBody DeviceQo qo) {
        deviceService.addDevice(qo);
        return ApiResult.success();
    }

    @Operation(summary = "更新设备", description = "修改某台设备的名称或所属产品")
    @PostMapping("update/{deviceId}")
    public ApiResult<Void> updateDevice(
            @Parameter(description = "设备 ID", required = true) @PathVariable String deviceId,
            @Parameter(description = "更新后的设备信息", required = true)
            @RequestBody DeviceQo qo) {
        qo.setId(deviceId);
        deviceService.updateDevice(qo);
        return ApiResult.success();
    }

    @Operation(summary = "删除设备", description = "根据设备 ID 删除设备")
    @GetMapping("del/{deviceId}")
    public ApiResult<Void> deleteDevice(@Parameter(description = "设备 ID", required = true) @PathVariable String deviceId) {
        deviceService.deleteDevice(deviceId);
        return ApiResult.success();
    }

    @Operation(summary = "查询单个设备", description = "根据设备 ID 获取设备详情")
    @GetMapping("selectOne/{deviceId}")
    public ApiResult<DeviceQo> getDevice(
            @Parameter(description = "设备 ID", required = true) @PathVariable String deviceId) {
        DeviceQo qo = deviceService.getDevice(deviceId);
        return qo == null ? ApiResult.fail(404, "设备不存在") : ApiResult.success(qo);
    }

    @Operation(summary = "查询所有设备", description = "获取所有已注册的设备列表")
    @GetMapping("selectAll/{deviceId}")
    public ApiResult<List<DeviceQo>> listDevices() {
        return ApiResult.success(deviceService.listDevices());
    }
}
